package com.smart.manager.task;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.smart.common.annotation.TaskBean;
import com.smart.common.annotation.TaskMethod;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.domain.TaskResult;
import com.smart.manager.product.entities.assembler.ReqRfid;
import com.smart.manager.product.entities.enums.RfidStatus;
import com.smart.manager.product.entities.models.BasicRfid;
import com.smart.manager.product.entities.models.query.QBasicRfid;
import com.smart.manager.system.repository.ConfigRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * 获取耳标任务
 * @author leo
 * @date 2023/09/06
 */
@Log4j2
@Component
@TaskBean
@RequiredArgsConstructor
public class RfidDataTask {

    private final ConfigRepository configRepository;
    private final CacheService cacheService;

    /**
     * 每小时更新耳标数据
     * TODO: 废弃
     * @return {@link TaskResult}
     */
    @TaskMethod(title = "每小时更新耳标数据")
    public synchronized TaskResult earTagData() {
        log.warn("准备更新耳标数据！");
        String url = (String) configRepository.readCache("Rfid").get("complex");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime createTimeStart = LocalDateTime.now();
        LocalDateTime createTimeEnd = createTimeStart.minusHours(6);
        HttpResponse res = HttpRequest.post(url)
                .header("subjectCode", (String) configRepository.readCache("Rfid").get("subjectCode"))
                .body(new JSONObject().set("page","1").set("pageSize","100000").set("createTimeStart",formatter.format(createTimeEnd)).set("createTimeEnd",formatter.format(createTimeStart)).toString())
                .timeout(20000).execute();
        if (res.isOk()){
            log.warn("耳标数据"+res.body());
            JSONObject entries = new JSONObject(res.body());
            if (entries.get("code").equals(200)){
                try {
                    Object data = new JSONObject(new JSONObject(entries.get("data"))).get("data");
                    List<ReqRfid.ReqRfidEar> reqRfidEars = JSONUtil.parseArray(data).toList(ReqRfid.ReqRfidEar.class);
                    List<BasicRfid> list = new QBasicRfid().findList();
                    cacheService.getRfidCache().put("name",reqRfidEars.stream().map(ReqRfid.ReqRfidEar::getBeaconMac).collect(Collectors.toSet()));
                    for (BasicRfid rfidData : list) {
                        List<ReqRfid.ReqRfidEar> collect = reqRfidEars.stream().filter(x -> x.getBeaconMac().equals(rfidData.getBeaconMac()))
                                .sorted(Comparator.comparing(ReqRfid.ReqRfidEar::getCreateTime).reversed()).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(collect)){
                            log.warn("最早的数据是:{}",collect.get(0));
                            LocalDateTime createTime = rfidData.getCreateTime();
                            BasicRfid basicRfid = rfidData;
                            BeanUtil.copyProperties(collect.get(0),rfidData);
                            if (rfidData.getRfidUpdateTime().equals(collect.get(0).getUpdateTime().format(DatePattern.createFormatter(DatePattern.NORM_DATETIME_PATTERN)))){
                                rfidData.setShake(basicRfid.getShake());
                            }else {
                                rfidData.setShake(basicRfid.getShake()+collect.get(0).getShake());
                            }
                            rfidData.setRfidUpdateTime(formatter.format(collect.get(0).getUpdateTime()));
                            rfidData.setCreateTime(createTime);
                            rfidData.setStatus(RfidStatus.ONLINE).update();
                        }else {
                            rfidData.setStatus(RfidStatus.OFFLINE);
                        }
                    }
                    return new TaskResult(true, "更新成功");
                }catch (Exception e){
                    e.printStackTrace();
                    return new TaskResult(false , "更新失败:"+e.getMessage());
                }
            }
        }
        return new TaskResult(false, "更新失败");
    }

}
